﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Vds2465Telegrams
{
	internal static class UserDataCommon
	{
		/// <summary>
		/// Convert the given byte array into an array that can be used in ToString methods
		/// </summary>
		/// <param name="nameOfBytes">name of the data in the byte array</param>
		/// <param name="bytes">the byte array</param>
		/// <returns>the generated string</returns>
		internal static string HexByteArrayToString(string nameOfBytes, byte[] bytes)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append(nameOfBytes ?? "<no name>");
			stringBuilder.Append("='");
			if (bytes == null)
			{
				stringBuilder.Append("<null>");
			}
			else if (bytes.Length == 0)
			{
				stringBuilder.Append("<empty>");
			}
			else
			{
				stringBuilder.Append("(");
				for (int index = 0; index < bytes.Length - 1; index++)
				{
					stringBuilder.Append("0x");
					stringBuilder.Append(bytes[index].ToString("X2"));
					stringBuilder.Append(", ");
				}
				stringBuilder.Append("0x");
				stringBuilder.Append(bytes[bytes.Length - 1].ToString("X2"));
				stringBuilder.Append(")");
			}

			stringBuilder.Append("'");

			return stringBuilder.ToString();
		}

		/// <summary>
		/// Checks if the two byte arrays have equal content.
		/// The sequence of bytes is considered, i.e. having the same byte set but a different order results in false
		/// </summary>
		/// <param name="bytes01"></param>
		/// <param name="bytes02"></param>
		/// <returns></returns>
		internal static bool Equals2ByteArrays(byte[] bytes01, byte[] bytes02)
		{
			if ((bytes01 != null) && (bytes02 != null))
			{
				if (bytes01.Length == bytes02.Length)
				{
					for (int index = 0; index < bytes02.Length; index++)
					{
						if (bytes01[index] != bytes02[index])
						{
							return false;
						}
					}

					return true;
				}

				return false;
			}

			// scenario where at least one byte array is null
			if ((bytes01 == null) && (bytes02 == null))
			{
				return true;
			}

			// scenario where only one byte array is null, we consider null and Length==0 to be equal
			if (bytes01 == null)
			{
				return (bytes02.Length == 0);
			}

			return (bytes01.Length == 0);
		}

		internal static byte GetHashCode_ByteArray(byte[] bytes)
		{
			byte hashCode = 0;

			if (bytes != null)
			{
				for (int index = 0; index < bytes.Length; index++)
				{
					hashCode ^= bytes[index];
				}
			}

			return hashCode;
		}
	}
}
